package com.game.config.web;


import cn.hutool.core.lang.ClassScanner;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.game.comment.core.AjaxResult;
import com.game.comment.core.RequestBody;
import com.game.comment.util.JsonUtil;
import com.game.config.netty.annotation.ActionController;
import com.game.config.netty.annotation.ActionMethod;
import com.game.config.netty.body.ActionBody;
import com.game.config.netty.server.ActionBeanInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/webSocketToUser/{id}", configurator = WebSocketConfig.class)
public class WebSocketToUser {

    private static final Logger log = LoggerFactory.getLogger(WebSocketToUser.class);
    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, WebSocketToUser> webSocketSet = new ConcurrentHashMap<>();
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private static Session session;

    // 指定的sid，具有唯一性
    private static String sid = "";

    private static ApplicationContext context;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session, EndpointConfig config) {
        // 获取WebsocketConfig.java中配置的“sessionId”信息值
        String httpSessionId = (String) config.getUserProperties().get("sessionId");
        WebSocketToUser.session = session;
        WebSocketToUser.sid = id;
        webSocketSet.put(sid, this);     // 加入set中
        addOnlineCount();           // 在线数加1
        log.info("用戶" + sid + "加入！当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  // 从set中删除
        subOnlineCount();               // 在线数减1
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws InvocationTargetException, IllegalAccessException, IOException {
        // 请求处理
        ActionBody actionBody = ActionBody.toBean(message);
        Integer mainRoute1 = actionBody.getMainRoute();
        Integer subRoute1 = actionBody.getSubRoute();
        String token = actionBody.getToken();
        cn.hutool.json.JSONObject data = actionBody.getData();
        String actionPackage = "com.game.modular.game.act";
        Set<Class<?>> classes = ClassScanner.scanPackageByAnnotation(actionPackage, ActionController.class);

        classes.forEach(clazz -> {
                String simpleName = clazz.getSimpleName();
                simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);

                ActionController actionController = clazz.getAnnotation(ActionController.class);
                int mainRoute = actionController.value();

                Method[] methods = clazz.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(ActionMethod.class)) {
                        ActionMethod annotation = method.getAnnotation(ActionMethod.class);
                        int subRoute = annotation.value();
                        if (mainRoute==mainRoute1 && subRoute==subRoute1){
                            Object bean = context.getBean(simpleName);
                            Method[] targets = bean.getClass().getDeclaredMethods();
                            Method method1 = null;
                            for (Method target : targets) {
                                if (target.getName().equals(method.getName())) {
                                    method1 = target;
                                    break;
                                }
                            }
                            assert method1 != null;
                            Class<?>[] parameterType = method.getParameterTypes();
                            // 方法参数列表
                            Object[] args = new Object[parameterType.length];
                            for (int i = 0; i < parameterType.length; i++) {
                                Class<?> aClass = parameterType[i];
                                args[0] = token;
                                Object bean1 = JSONUtil.toBean(data, aClass);
                                args[i]= bean1;
                            }
                            try {
                                Object result = method.invoke(bean, args);
                                sendToUser(JSONUtil.toJsonStr(result), sid);
                                System.err.println(result);
                            } catch (IllegalAccessException | InvocationTargetException | IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
        });
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        error.printStackTrace();
        sendToUser("发生错误请重试", sid);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public boolean sendToUser(String message, String sendUserId) throws IOException {
        if (webSocketSet.get(sendUserId) != null) {
            if (!sid.equals(sendUserId)) {
                return false;
                // webSocketSet.eqlist(sendUserId).sendMessage("用户" + sendUserId + "发来消息：" + message);
            } else {
                webSocketSet.get(sendUserId).sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return true;
            }
        } else {
            // 如果用户不在线则返回不在线信息给自己  日常
            return false;
        }
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketToUser.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketToUser.onlineCount--;
    }
}
